package com.abe.libcore.base.screen

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.text.TextUtils
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast

abstract class AbeFragment : BScreenFragment() {
    private val appToast: Int = 0x999
    lateinit var rootView: View

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                              savedInstanceState: Bundle?): View {
        rootView = inflater.inflate(getLayoutRes(), container, false)
        if (isAutoZoom() && getScale() != 1.0F)
            RelayoutTool.relayoutViewHierarchy(rootView, getScale())
        initContent()
        return rootView
    }

    protected abstract fun getLayoutRes(): Int

    protected abstract fun initContent()
    /**********************************************************************************************/
    inner class BaseHandler(looper: Looper) : Handler(looper) {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            when (msg?.what) {
                appToast -> Toast.makeText(getContext(), msg.obj.toString(), Toast.LENGTH_SHORT).show()
                else -> if (isImp(this@AbeFragment.javaClass, OnHandlerListener::class.java)) {
                    (this@AbeFragment as OnHandlerListener).dispatchHandleMessage(msg)
                }
            }
        }
    }

    protected fun toast(content: String) {
        if (TextUtils.isEmpty(content)) return
        localSendMsg(appToast, content)
    }

    protected fun localSendMsg(what: Int, obj: Any) {
        getHandler().sendMessage(getMessage(what, obj))
    }

    //获取Message
    private fun getMessage(what: Int, obj: Any): Message? {
        val msg = Message()
        msg.what = what
        msg.obj = obj
        return msg
    }

    //获取Handler
    protected fun getHandler(): BaseHandler {
        return BaseHandler(Looper.getMainLooper())
    }

    /**
     * 是否实现接口
     * @param a 类
     * @param b 接口
     */
    protected fun isImp(a: Class<*>, b: Class<*>): Boolean {
        return b.isAssignableFrom(a)
    }
}